<?php

namespace App\Admin\Repositories;

use App\Models\Activity as Model;
use Dcat\Admin\Repositories\EloquentRepository;
use Dcat\Admin\Form;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use App\Models\Vehicle as VehicleModel;

class Activity extends EloquentRepository
{
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;

    public function store(Form $form)
    {
        $result = null;

        DB::transaction(function () use ($form, &$result) {
            $model = $this->model();

            $updates = $form->updates();

            [$relations, $relationKeyMap] = $this->getRelationInputs($model, $updates);

            if ($relations) {
                $updates = Arr::except($updates, array_keys($relationKeyMap));
            }

            foreach ($updates as $column => $value) {
                $model->setAttribute($column, $value);
            }

            $result = $model->save();
            if (isset($relations['vehicles'])) {
                !empty($relations['vehicles']) && VehicleModel::whereIn('id', $relations['vehicles'])->update(['activity_id' => $model->getKey()]);

                unset($relations['vehicles']);
                unset($relationKeyMap['vehicles']);
            }
            $this->updateRelation($form, $model, $relations, $relationKeyMap);
        });

        return $this->model()->getKey();
    }

    public function update(Form $form)
    {
        /* @var EloquentModel $builder */
        $model = $this->model();

        if (!$model->getKey()) {
            $model->exists = true;

            $model->setAttribute($model->getKeyName(), $form->getKey());
        }

        $result = null;

        DB::transaction(function () use ($form, $model, &$result) {
            $updates = $form->updates();

            [$relations, $relationKeyMap] = $this->getRelationInputs($model, $updates);

            if ($relations) {
                $updates = Arr::except($updates, array_keys($relationKeyMap));
            }

            foreach ($updates as $column => $value) {
                /* @var EloquentModel $model */
                $model->setAttribute($column, $value);
            }

            $result = $model->update();
            if (isset($relations['vehicles'])) {
                !empty($relations['vehicles']) && VehicleModel::whereIn('id', $relations['vehicles'])->update(['activity_id' => $model->getKey()]);
                VehicleModel::whereNotIn('id', $relations['vehicles'])->where('activity_id', $model->getKey())->update(['activity_id' => null]);

                unset($relations['vehicles']);
                unset($relationKeyMap['vehicles']);
            }

            $this->updateRelation($form, $model, $relations, $relationKeyMap);
        });

        return $result;
    }
}
